package com.foogui.primary.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class FibonacciTest {
    static class Fibonacci extends RecursiveTask<Integer>{
        int n=0;

        public Fibonacci(int n) {
            this.n = n;
        }

        @Override
        protected Integer compute() {
            if (n<2){
                return n;
            }
            Fibonacci f1 = new Fibonacci(n - 1);
            f1.fork();
            Fibonacci f2 = new Fibonacci(n - 2);
            f2.fork();

            return f1.join()+f2.join();
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("CPU核数：" + Runtime.getRuntime().availableProcessors());
        long l1 = System.currentTimeMillis();
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Integer> task = pool.submit(new Fibonacci(40));
        System.out.println(task.get());
        long l2 = System.currentTimeMillis();
        System.out.println(String.format("耗时：%d millis", l2 - l1));
    }
}
